/* 服务入口 */
const http = require('http')
// event模块
const event = require('events')
// 创建 eventEmitter 用于自定义事件
const EventEmitter = new event.EventEmitter()
// fs
const fs = require('fs')
let fsData = ''

/* 创建服务 */
http.createServer((request, response) => {
  // 发送头部数据
  response.writeHead(200, { 'Content-Type': 'text/Plain' })
  // 发送响应数据
  response.end('hello word! wellcome!')
  EventEmitter.emit('res-success')
}).listen(8888)
// 自定义事件监听
EventEmitter.on('res-success', () => {
  
})
// 文件流写入
const writerStream = fs.createWriteStream('./file/input.txt')
const writeData = '将本段文字写入~将本段文字写入~将本段文字写入~'
// 用utf-8写入
writerStream.write(writeData, 'utf-8')
// 标记文件末尾
writerStream.end()
// 文件写入事件
writerStream.on('finish', () => {
  // 文件流读取
  const readStream = fs.createReadStream('./file/input.txt')
  // 设置编码
  readStream.setEncoding('utf-8')
  // 处理事件流 data当有数据可读时触发 , end没有更多的数据可读时触发, error在接收和写入过程中发生错误时触发
  readStream.on('data', chunk => {
    fsData += chunk
  })
  readStream.on('end', chunk => {
    console.log(fsData)
  })
  readStream.on('error', err => {
    console.log(err.stack)
  })
})
writerStream.on('error', err => {
  console.log(err.stack)
})
// 管道流 用于大文件的复制
const writerStream2 = fs.createWriteStream('./file/pieOut.txt')
const readStream2 = fs.createReadStream('./file/pieInput.txt')
// 读取文件并写入文件
readStream2.pipe(writerStream2)

/* 链式流，这里用来压缩和解压文件 */
// const zLib = require('zlib')
// readStream2.pipe(zLib.createGzip).pipe(fs.createWriteStream('./file/input.txt.gz'))

/* 引入模块 */
const hello = require('./modules/hello')
hello.world()  
/* 打印启动信息 */
console.log('server run success at 192.168.2.174:8888')